package com.linln.wtp.controller.user;

import com.linln.common.enums.RoleEnum;
import com.linln.common.utils.SessionUtil;
import com.linln.common.vo.JsonResult;
import com.linln.component.cache.util.RedisUtil;
import com.linln.component.wtpshiro.annotation.UserLoginToken;
import com.linln.modules.shopsService.service.ShopsService;
import com.linln.modules.system.domain.Role;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.service.UserService;
import com.linln.modules.ticket.service.TicketService;
import com.linln.modules.vehicle.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.wtp.controller.user
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.wtp.controller.user
 * @Description: TODO
 * @date Date : 2020年11月26日 11:01
 */
@RestController()
@RequestMapping("/user")
@Slf4j
public class WTPUserController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private TicketService ticketService;
    @Autowired
    private VehicleService vehicleService;
    //JPA
    @Autowired
    private ShopsService shopsService;
    @Value("${server.ip}")
    private String ip;

    //获取登录的用户信息
    @UserLoginToken
    @GetMapping("/info")
    public Map<String, Object> getUserInfo() {
        Map<String, Object>  map = new HashMap<>();
        try {
            User user = userService.getById(SessionUtil.getUserId());
            List<Map<String, Object>> shops = shopsService.getByUserShops(user.getId());
            map.put("shopList", shops);
            if (user.getHeadImg().contains("thirdwx.qlogo.cn")) {
                map.put("headPortrait", user.getHeadImg());
            } else {
                map.put("headPortrait", ip + user.getHeadImg());
            }

            map.put("phone", user.getPhone());
            map.put("name", user.getUsername());
            map.put("ticketTotal", ticketService.getAllTicketCount(SessionUtil.getUserId()));
            map.put("integral", user.getPointsLeft());
            map.put("vehicleCount", vehicleService.getVehicle(SessionUtil.getUserId()));
            map.put("isStaff", false);
            Set<Role> roles = user.getRoles();
            map.put("isGetCar", false);
            for (Role role : roles) {
                if (RoleEnum.TAKECARUSER.getCode().equals(role.getId())) {
                    map.put("isGetCar", true);
                }
            }
            //店铺角色是否有
            if (shops.size() > 0) {
                ok:
                for (Role item : roles) {
                    if (RoleEnum.PM.getCode().equals(item.getId()) || RoleEnum.STAFF.getCode().equals(item.getId())) {
                        for (Map m : shops) {
                            String audit = (String) m.get("audit_mark");
                            if (Strings.isNotBlank(audit) && audit.equals("1")) {
                                map.put("isStaff", true);
                                break ok;
                            }
                        }
                    }
                }
            }
            //是否赠送
            Object o = redisUtil.get(SessionUtil.getToken() + "isGive");
            if (o != null) {
                ((Map) o).put("isGive", true);
                map.put("giveInfo", o);
            } else {
                map.put("giveInfo", new HashMap<String, Object>() {{
                    put("isGive", false);
                }});
            }
            Map<String, Object> giveMap = ticketService.giveCanGiveActivity(user.getId());
            map.put("code", "200");
            map.put("msg", "获取用户信息成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            map.put("code", "500");
            map.put("msg", "获取用户信息失败");
        }
        return map;
    }

    //获取用户的详细信息
    @UserLoginToken
    @GetMapping("/detailedInfo")
    public JsonResult getUserDetailedInfo() {
        Map<String, Object> map = new HashMap<>();
        try {
//            String token = (String) SessionUtil.getRequest().getAttribute("token");
//            Long userId = ((User) SecurityUtils.getSubject().getPrincipal()).getId();
            User user = userService.getById(SessionUtil.getUserId());
            if (user.getHeadImg().contains("thirdwx.qlogo.cn")) {
                map.put("headImg", user.getHeadImg());
            } else {
                map.put("headImg", ip + user.getHeadImg());
            }
            map.put("phone", user.getPhone());
            map.put("username", user.getUsername());
            map.put("nickname", user.getNickname());
            if (Strings.isBlank(user.getIdcard())) {
                map.put("idcard", user.getIdcard());
                map.put("isEdit", false);
            } else {
                map.put("idcard", user.getIdcard().replaceAll("(\\d{4})\\d{10}(\\d{4})", "$1****$2"));
                map.put("isEdit", true);
            }
            map.put("birthday", user.getBirthday());
            map.put("sex", user.getSex() != null ? user.getSex() == 1 ? "男" : "女" : null);
            //系统当前时间前端要用
            map.put("endDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        } catch (Exception e) {
            log.error(e.getMessage());
            JsonResult.error("获取用户信息失败");
        }
        return JsonResult.ok().put("data", map);
    }

    /**
     * 修改用户信息 哪一个有值修改哪个
     *
     * @param headImg  用户头像
     * @param username 用户名
     * @param phone    用户手机号码
     * @param nickname 用户真实姓名
     * @param idcard   证件号码
     * @param birthday 用户生日
     * @param sex      性别 1男 2女
     */
    @UserLoginToken
    @PostMapping("updateUserInfo")
    public JsonResult updateUserInfo(String headImg, String username, String phone, String nickname, String idcard, String birthday, Byte sex) {
        try {
            userService.updateUserInfo(headImg, username, phone, nickname, idcard, birthday, sex, SessionUtil.getUserId());
        } catch (Exception e) {
            log.error(e.getMessage());
            return JsonResult.error("保存失败");
        }
        return JsonResult.ok("保存成功");
    }


    @UserLoginToken
    @PostMapping(value = "/updateUserHeadImg")
    //通过base64字符串 保存图片
    public Map<String, Object> saveImgBase64(String img) {
        return ticketService.saveVerificationImgByBase64(img);
    }
}
